//
//  FindPlaceViewController.m
//  Gruphoto
//
//  Created by Thao Nguyen Huy on 1/7/13.
//  Copyright (c) 2013 CNC Software. All rights reserved.
//

#import "FindPlaceViewController.h"
#import "CreateViewController.h"
#import "PlaceViewCell.h"
#import <FacebookSDK/FacebookSDK.h>
#import "GruphotoAppDelegate.h"

@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed:@"background_navigation_bar.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end


@interface FindPlaceViewController ()

@end

@implementation FindPlaceViewController
@synthesize placeTableView, placeSearchBar, placeMapView, maskView, selectAnnotationButton;
@synthesize places = _places, placesNeedDisplay, hiddenView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        UIImageView *titleImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"title_gruphoto.png"]];
        self.navigationItem.titleView = titleImageView;
        [titleImageView release];
        
        UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [cancelButton setBounds:CGRectMake(0, 0, 51, 30)];
        [cancelButton setBackgroundImage:[UIImage imageNamed:@"button_cancel.png"] forState:UIControlStateNormal];
        [cancelButton addTarget:self action:@selector(cancelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *cancelButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];
        self.navigationItem.leftBarButtonItem = cancelButtonItem;
        [cancelButtonItem release];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"background_navigation_bar.png"]
                                                      forBarMetrics:UIBarMetricsDefault];
    }
    placeSearchBar.backgroundImage = [UIImage imageNamed:@"background_searchbar.png"];
    self.view.backgroundColor = [UIColor colorWithRed:226/255.0 green:231/255.0 blue:237/255.0 alpha:1.0];
    hiddenView.backgroundColor = [UIColor colorWithRed:226/255.0 green:231/255.0 blue:237/255.0 alpha:1.0];
    for (UIView *subview in placeMapView.subviews) {
        if ([subview isKindOfClass:[UILabel class]]) {
            subview.hidden = YES;
            break;
        }
    }
    placeTableView.bounces = YES;
    self.places = [NSMutableArray array];
    [[GruphotoAppDelegate sharedDelegate] showHUDWithStatus:@"Loading..."];
    [FBRequestConnection startForPlacesSearchAtCoordinate:[GruphotoAppDelegate sharedDelegate].currentLocation.coordinate radiusInMeters:100 resultsLimit:50 searchText:nil completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
        [[GruphotoAppDelegate sharedDelegate] hideHUD];        
        if (error) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error message", @"")
                                                                message:[error localizedDescription]
                                                               delegate:nil
                                                      cancelButtonTitle:NSLocalizedString(@"OK", @"")
                                                      otherButtonTitles:nil];
            [alertView show];
            [alertView release];
        }
        else {
            FBGraphObject *responseData = (FBGraphObject *)result;
            for (FBGraphObject *place in [responseData objectForKey:@"data"]) {
                if (![[[place objectForKey:@"location"] objectForKey:@"street"] isEqualToString:@""]) {
                    [_places addObject:place];
                }
            }
            [self resetSearch];            
            [placeTableView reloadData];
        }
    }];
    placeTableView.contentOffset = CGPointMake(0, -120);
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    placeMapView.hidden = NO;
    MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance([GruphotoAppDelegate sharedDelegate].currentLocation.coordinate, 1000, 1000);
    MKCoordinateRegion adjustedRegion = [placeMapView regionThatFits:viewRegion];
    [placeMapView setRegion:adjustedRegion animated:YES];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.placeSearchBar = nil;
    self.placeTableView = nil;
    self.placeMapView = nil;
    self.maskView = nil;
    self.selectAnnotationButton = nil;
    self.hiddenView = nil;
}

- (void)dealloc {
    [placeSearchBar release];
    [placeTableView release];
    [placeMapView release];
    [maskView release];
    [selectAnnotationButton release];
    [hiddenView release];
    self.places = nil;
    self.placesNeedDisplay = nil;
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Custom methods
- (void)resetSearch {
    NSMutableArray *placesCopy = [self.places mutableCopy];
	self.placesNeedDisplay = placesCopy;
	[placesCopy release];
}

- (void)handleSearchForTerm:(NSString *)searchTerm {
	NSMutableArray *placesToRemove = [[NSMutableArray alloc] init];
	[self resetSearch];
    for (FBGraphObject *place in placesNeedDisplay) {
        NSString *placeName = [place objectForKey:@"name"];
        NSString *placeAddress = [[place objectForKey:@"location"] objectForKey:@"street"];
        if ([placeName rangeOfString:searchTerm
                        options:NSCaseInsensitiveSearch].location == NSNotFound &&
            [placeAddress rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound) {
            [placesToRemove addObject:place];
        }
    }
    [placesNeedDisplay removeObjectsInArray:placesToRemove];
	[placesToRemove release];
    for (FBGraphObject *obj in placesNeedDisplay) {
        NSString *placeName = [obj objectForKey:@"name"];
        NSString *placeAddress = [[obj objectForKey:@"location"] objectForKey:@"street"];
        NSLog(@"Name: %@, add: %@", placeName, placeAddress);        
    }
	[placeTableView reloadData];
}

#pragma mark - Action methods
- (void)resignKeyboard {
    [placeSearchBar resignFirstResponder];
    maskView.hidden = YES;
}

- (IBAction)cancelButtonPressed:(id)sender {
    placeMapView.hidden = YES;
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)selectAnnotationButtonPressed:(id)sender {
    UIButton *button = (UIButton *)sender;
    button.selected = !button.selected;
    if (button.selected) {
        [placeMapView selectAnnotation:placeMapView.userLocation animated:YES];
    }
    else {
        [placeMapView deselectAnnotation:placeMapView.userLocation animated:YES];
    }
}

- (IBAction)maskViewTapped:(id)sender {
    [self resignKeyboard];
    [placeTableView setContentOffset:CGPointMake(0, -120) animated:YES];
}

#pragma mark - UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    maskView.hidden = NO;
    [placeTableView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self resignKeyboard];
    [placeTableView setContentOffset:CGPointMake(0, -120) animated:YES];
	NSString *searchTerm = [searchBar text];
	[self handleSearchForTerm:searchTerm];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchTerm {
	if ([searchTerm length] == 0) {
		[self resetSearch];
		[placeTableView reloadData];
		return;
	}
	[self handleSearchForTerm:searchTerm];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSLog(@"offset: %f", placeTableView.contentOffset.y);
    dispatch_async(dispatch_get_main_queue(), ^{
        CGRect frame;
        frame = selectAnnotationButton.frame;
        frame.origin.y = 49 + (-120 - placeTableView.contentOffset.y) / 2;
        selectAnnotationButton.frame = frame;
        if (placeTableView.contentOffset.y < 44) {
            float y = -200 + (-120 - placeTableView.contentOffset.y) / 2;
            frame = placeMapView.frame;
            frame.origin.y = y;
            placeMapView.frame = frame;
            
            frame = hiddenView.frame;
            frame.origin.y = -placeTableView.contentOffset.y;
            hiddenView.frame = frame;
        }
    });
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (maskView.hidden) {
      return (placesNeedDisplay.count > 0 ? placesNeedDisplay.count + 1 : 0);  
    }
    else {
        return placesNeedDisplay.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PlaceViewCell *cell = (PlaceViewCell *)[tableView dequeueReusableCellWithIdentifier:[PlaceViewCell identifier]];
    if (cell == nil) {
        cell = [PlaceViewCell cellFromNib];
    }
    
    FBGraphObject *place_ = nil;
    if (maskView.hidden) {
        if (indexPath.row == 0) {
            place_ = [placesNeedDisplay objectAtIndex:indexPath.row];
            cell.placeNameLabel.textColor = [UIColor colorWithRed:71/255.0 green:138/255.0 blue:197/255.0 alpha:1.0];
            cell.placeNameLabel.text = @"Outdoor (unknown place)";
        }
        else {
            place_ = [placesNeedDisplay objectAtIndex:indexPath.row - 1];
            cell.placeNameLabel.textColor = [UIColor blackColor];
            cell.placeNameLabel.text = [place_ objectForKey:@"name"];
        }
    }
    else {
        place_ = [placesNeedDisplay objectAtIndex:indexPath.row];
        cell.placeNameLabel.textColor = [UIColor blackColor];
        cell.placeNameLabel.text = [place_ objectForKey:@"name"];        
    }

    cell.placeAddressLabel.text = [[place_ objectForKey:@"location"] objectForKey:@"street"];
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [placeSearchBar resignFirstResponder];
    CreateViewController *createViewController = [[CreateViewController alloc] initWithNibName:@"CreateViewController" bundle:nil];
    createViewController.editMode = EventEditModeCreate;
    createViewController.placeType = indexPath.row;
    if (indexPath.row == 0) {
        createViewController.place = [_places objectAtIndex:indexPath.row];
    }
    else {
        createViewController.place = [_places objectAtIndex:indexPath.row - 1];
    }
    [self.navigationController pushViewController:createViewController animated:YES];
    [createViewController release];
}

@end
